import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * 
 * @author Jacob
 *
 */

public class SerializationController extends AbstractDataController implements
        Serializable
{
	private transient static final long serialVersionUID = 1L;
	private transient static final File DEFAULT_DATAFIL = 
		new File("c:\\data.bin");
	private File datafil = null;
	private BookingDatabase bookingDB = null;
	private HytteDatabase hytteDB = null;
	private KundeDatabase kundeDB = null;
	private PrisDatabase prisDB = null;

	public SerializationController(IDataErrorHandler errorHandler, File datafil)
	{
		super(errorHandler);

		this.datafil = datafil;
		if (!datafil.exists())
		{
			try
			{
				datafil.createNewFile();

			}

			catch (IOException ioe)
			{
				Exception e = new Exception("Kunne ikke oprette en ny database");
				errorHandler.onDataError(e);
			}

			firstRun();
		}

		else
			load();
	}

	public SerializationController(IDataErrorHandler errorHandler)
	{
		this(errorHandler, DEFAULT_DATAFIL);
	}

	private void firstRun()
	{
		kundeDB = new KundeDatabase(this, new ArrayList<Kunde>());
		hytteDB = new HytteDatabase(this);
		bookingDB = new BookingDatabase(this, hytteDB);
		prisDB = new PrisDatabase(this);

		save();
	}

	private void load()
	{
		try
		{
			ObjectInputStream stream = new ObjectInputStream(
			        new FileInputStream(datafil));

			SerializationController controller = (SerializationController) stream
			        .readObject();

			kundeDB = controller.getKundeDatabase();
			hytteDB = controller.getHytteDatabase();
			bookingDB = controller.getBookingDatabase();
			prisDB = controller.getPrisDatabase();

			stream.close();
		}

		catch (Exception e)
		{
			getErrorHandler().onDataError(e);
		}
	}

	@Override
	public void save()
	{
		try
		{
			ObjectOutputStream stream = new ObjectOutputStream(
			        new FileOutputStream(datafil));

			stream.writeObject(this);
			stream.close();
		}

		catch (IOException ioe)
		{
			getErrorHandler().onDataError(ioe);
		}

	}

	@Override
	public BookingDatabase getBookingDatabase()
	{
		return bookingDB;
	}

	@Override
	public HytteDatabase getHytteDatabase()
	{
		return hytteDB;
	}

	@Override
	public KundeDatabase getKundeDatabase()
	{
		return kundeDB;
	}

	@Override
	public PrisDatabase getPrisDatabase()
	{
		return prisDB;
	}

}
